<template>
      <!-- 页面头部 -->
      <div class="header-section">
        <div class="header-content">
          <div class="title-section">
            <h2 class="page-title">
              <i class="el-icon-office-building"></i> 旅行社信息管理
            </h2>
            <p class="page-subtitle">管理旅行社相关信息及审核状态</p>
          </div>
          <div class="total-count">
            <div class="count-card">
              <span class="count-label">旅行社总数</span>
              <span class="count-value">{{ total }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 精简后的筛选栏 -->
      <div class="search-filter-card">
        <div class="filter-group">
          <div class="filter-row">
            <div class="filter-item">
              <label class="filter-label">
                <i class="el-icon-office-building"></i> 旅行社名称
              </label>
              <el-input 
                v-model="filterParams.travelAgencyName" 
                placeholder="请输入旅行社名称" 
                clearable 
                class="filter-input" />
            </div>
            <div class="filter-item">
              <label class="filter-label">
                <i class="el-icon-document-checked"></i> 审核状态
              </label>
              <el-select 
                v-model="filterParams.auditStatus" 
                placeholder="请选择状态" 
                clearable 
                class="filter-select">
                <el-option label="通过" value="通过" />
                <el-option label="未通过" value="未通过" />
                <el-option label="未审核" value="未审核" />
              </el-select>
            </div>
            <div class="filter-item">
              <label class="filter-label">
                <i class="el-icon-date"></i> 注册时间
              </label>
              <el-date-picker 
                v-model="filterParams.registrationTime" 
                type="daterange" 
                range-separator="至"
                start-placeholder="开始日期" 
                end-placeholder="结束日期" 
                value-format="YYYY-MM-DD" 
                class="compact-date-picker" />
            </div>
          </div>
        </div>
        <div class="action-buttons">
          <el-button 
            type="primary" 
            @click="handleFilter" 
            class="search-btn">
            筛选
          </el-button>
          <el-button 
            @click="resetFilter" 
            class="reset-btn">
            重置
          </el-button>
          <el-button 
            type="danger" 
            @click="handleBatchDelete" 
            :disabled="selectedItems.length === 0" 
            class="batch-delete-btn">
            批量删除
          </el-button>
        </div>
      </div>
      
      <!-- 数据表格和分页区域 -->
      <div class="table-and-pagination">
        <!-- 数据表格区域 -->
        <div class="data-table-card">
          <el-table 
            :data="tableData" 
            class="data-table" 
            @selection-change="handleSelectionChange" 
            v-loading="loading"
            stripe 
            border 
            height="100%"
            style="width: 100%;"
          >
            <el-table-column type="selection" width="60" fixed />
            <el-table-column label="编号" width="120">
              <template #default="scope">
                <span>{{ formatAgencyCode(scope.$index, pagination.currentPage, pagination.pageSize) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="travelAgencyName" label="旅行社名称" width="220" />
            <el-table-column prop="officePhone" label="办公电话" width="180" />
            <el-table-column prop="auditStatus" label="审核状态" width="140">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.auditStatus)">
                  {{ row.auditStatus }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="registrationTime" label="注册时间" width="200" sortable>
              <template #default="{ row }">
                <div class="time-cell">
                  <i class="el-icon-time"></i>
                  <span>{{ formatTime(row.registrationTime) }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
              <template #default="scope">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="handleDetail(scope.row.travelAgencyId)">
                  详情
                </el-button>
                <el-button 
                  size="small" 
                  class="delete-btn" 
                  @click="handleDelete(scope.row.travelAgencyId)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-wrapper">
          <el-pagination 
            v-model:current-page="pagination.currentPage" 
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]" 
            :background="true" 
            layout="total, sizes, prev, pager, next, jumper"
            :total="total" 
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange" />
        </div>
      </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Filter, Refresh, Delete, View } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router'

const regionList = ref([]) // 用于存储地区表数据
const router = useRouter()
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const selectedItems = ref([])

// 省份和城市选项数据
const provinceOptions = ref(['广东省', '江苏省', '浙江省', '四川省', '山东省', '福建省', '湖南省', '湖北省'])
const cityOptions = ref(['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '南京', '西安', '重庆'])

// 查询参数（全字段搜索）
const queryParams = ref({
  keyword: ''
})

// 筛选参数（精确筛选）
const filterParams = ref({
  travelAgencyName: '',
  province: '',
  city: '',
  auditStatus: '',
  registrationTime: []
})

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10
})

// 格式化时间显示
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '通过': return 'success'
    case '未通过': return 'danger'
    case '未审核': return 'warning'
    default: return 'info'
  }
}

// 编号格式化函数：A+5位数字（自增）
const formatAgencyCode = (index, currentPage, pageSize) => {
  const num = (currentPage - 1) * pageSize + index + 1
  return `A${num.toString().padStart(5, '0')}`
}

// 构建请求参数
const buildRequestParams = () => {
  const params = {
    pageNum: pagination.value.currentPage,
    pageSize: pagination.value.pageSize
  }

  // 查询参数（全字段搜索）
  if (queryParams.value.keyword) {
    params.keyword = queryParams.value.keyword
    return params  // 查询时忽略筛选条件
  }

  // 筛选参数（精确筛选）
  if (filterParams.value.travelAgencyName) {
    params.travelAgencyName = filterParams.value.travelAgencyName
  }
  if (filterParams.value.province) {
    params.province = filterParams.value.province
  }
  if (filterParams.value.city) {
    params.city = filterParams.value.city
  }
  if (filterParams.value.auditStatus) {
    params.auditStatus = filterParams.value.auditStatus
  }
  if (filterParams.value.registrationTime && filterParams.value.registrationTime.length === 2) {
    params.startTime = filterParams.value.registrationTime[0] + ' 00:00:00'
    params.endTime = filterParams.value.registrationTime[1] + ' 23:59:59'
  }

  return params
}

// 获取旅行社列表
const fetchData = async () => {
  try {
    loading.value = true
    const params = buildRequestParams()

    const response = await axios.get("http://localhost:8080/mw/travelAgency/list", { params })
    console.log('接口返回内容:', response.data)
    const resData = response.data
    if (Array.isArray(resData.list)) {
      total.value = resData.total || resData.list.length
      tableData.value = resData.list
    } else {
      throw new Error('获取数据失败')
    }
  } catch (error) {
    ElMessage.error('获取旅行社数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 查询（全字段搜索）
const handleSearch = () => {
  // 重置筛选条件
  resetFilter(false)
  pagination.value.currentPage = 1
  fetchData()
}

// 筛选（精确筛选）
const handleFilter = () => {
  // 清空查询关键词
  queryParams.value.keyword = ''
  pagination.value.currentPage = 1
  fetchData()
}

// 重置筛选
const resetFilter = (shouldFetch = true) => {
  filterParams.value = {
    travelAgencyName: '',
    province: '',
    city: '',
    auditStatus: '',
    registrationTime: []
  }
  if (shouldFetch) {
    pagination.value.currentPage = 1
    fetchData()
  }
}

// 查看详情
const handleDetail = (id) => {
  router.push({ name: 'AgencyAudit', params: { id } })
}

// 删除旅行社
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除这条旅行社记录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    loading.value = true
    const response = await axios.delete(`/mw/travelAgency/delete/${id}`)
    if (response.data > 0) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
    }
  } finally {
    loading.value = false
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定删除选中的${selectedItems.value.length}条旅行社记录吗?`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    const ids = selectedItems.value.map(item => item.travelAgencyId)
    const response = await axios.post('/mw/travelAgency/batchDelete', { ids })

    if (response.data > 0) {
      ElMessage.success(`成功删除${response.data}条记录`)
      fetchData()
      selectedItems.value = []
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败: ' + (error.response?.data?.message || error.message))
    }
  } finally {
    loading.value = false
  }
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedItems.value = selection
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  fetchData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  fetchData()
}

// 初始化加载数据
onMounted(() => {
  fetchData()
  // 获取地区表数据
  axios.get("http://localhost:8080/api/regions").then((response) => {
    regionList.value = response.data
  }).catch(error => {
    console.error('获取地区数据失败', error)
  })
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  min-height: calc(100vh - 40px); /* 修改：使用min-height代替固定高度 */
  box-sizing: border-box;
  background-color: #f0f2f5;
  display: flex;
  flex-direction: column;
}

.box-card {
  max-width: 1600px;
  margin: 0 auto;
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden; /* 新增：防止内容溢出 */
}

/* 表格和分页区域 */
.table-and-pagination {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0; /* 重要：防止flex项目溢出 */
  overflow: hidden; /* 新增：防止内容溢出 */
  
  .data-table-card {
    flex: 1;
    min-height: 0; /* 新增：确保可以收缩 */
    overflow: hidden;
    width: 100%;
    :deep(.el-table) {
      height: 100% !important;
    }
  }
  
  .pagination-wrapper {
    flex-shrink: 0; /* 防止分页被压缩 */
    padding: 16px 0;
    background: white;
    border-top: 1px solid #ebeef5;
    position: sticky;
    bottom: 0;
    z-index: 2;
  }
}

/* 头部样式 */
.header-section {
  background: linear-gradient(135deg, #a0c4e4 0%, #7fa8d1 100%);
  padding: 20px 25px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(160, 196, 228, 0.2);
  margin-bottom: 24px;
  color: #2c3e50;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  .page-title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 10px;
    
    i {
      font-size: 28px;
      color: #2c3e50;
    }
  }
  
  .page-subtitle {
    margin: 5px 0 0;
    font-size: 14px;
    color: #4a5568;
  }
}

.total-count {
  .count-card {
    background: rgba(255, 255, 255, 0.7);
    padding: 12px 20px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    border: 1px solid #e2e8f0;
    
    .count-label {
      font-size: 14px;
      margin-bottom: 5px;
      color: #4a5568;
    }
    
    .count-value {
      font-size: 24px;
      font-weight: 700;
      color: #2c3e50;
    }
  }
}

/* 搜索筛选卡片 */
.search-filter-card {
  background-color: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  margin-bottom: 20px;
  
  :deep(.el-input-group__append) {
    background-color: #409EFF;
    color: white;
    
    .el-button {
      color: white;
    }
  }
}

.filter-group {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.filter-row {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  
  .filter-label {
    font-size: 14px;
    color: #606266;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 6px;
    font-weight: 500;
    
    i {
      font-size: 16px;
    }
  }
  
  .filter-input {
    :deep(.el-input__inner) {
      border-radius: 8px;
      height: 40px;
      line-height: 40px;
    }
  }
  
  .filter-select {
    width: 100%;
    
    :deep(.el-input__inner) {
      border-radius: 8px;
      height: 40px;
      line-height: 40px;
    }
  }
  
  .compact-date-picker {
    width: 100%;
    
    :deep(.el-input__inner) {
      height: 36px;
      line-height: 36px;
    }
    
    :deep(.el-date-editor .el-range-separator) {
      line-height: 36px;
      padding: 0 8px;
      width: auto;
    }
    
    :deep(.el-date-editor .el-range-input) {
      height: 36px;
      width: 38%;
    }
    
    :deep(.el-date-editor .el-range__close-icon) {
      line-height: 36px;
    }
    
    :deep(.el-date-editor .el-range__icon) {
      line-height: 36px;
    }
  }
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  
  .search-btn {
    background: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
    border: none;
    border-radius: 8px;
    padding: 10px 20px;
    height: 40px;
    
    &:hover {
      opacity: 0.9;
    }
  }
  
  .reset-btn {
    border-radius: 8px;
    padding: 10px 20px;
    height: 40px;
    border: 1px solid #dcdfe6;
    
    &:hover {
      color: #4299e1;
      border-color: #c6e2ff;
      background-color: #ecf5ff;
    }
  }
  
  .batch-delete-btn {
    border-radius: 8px;
    padding: 10px 20px;
    height: 40px;
    
    &:hover {
      opacity: 0.9;
    }
    
    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }
  }
}

/* 数据表格卡片 */
.data-table-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  margin-bottom: 0;
  
  :deep(.el-table) {
    border-radius: 12px 12px 0 0;
    overflow: hidden;
    
    th {
      background-color: #f8fafc !important;
      font-weight: 600;
      color: #4a5568;
    }
    
    td {
      padding: 12px 0;
    }
    
    .el-table__row:hover {
      background-color: #f0f4f8;
    }
  }
}

.time-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  color: #718096;
  
  i {
    font-size: 16px;
  }
}

/* 分页样式 */
.pagination-wrapper {
  margin-top: 0;
  display: flex;
  justify-content: center;
  
  :deep(.el-pagination) {
    /* 重置分页基础样式 */
    font-size: 14px;
    padding: 2px 5px;
    color: #606266;
    
    /* 按钮样式 */
    .btn-prev,
    .btn-next {
      min-width: 32px;
      height: 32px;
      line-height: 32px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      background-color: #fff;
      
      &:hover {
        color: #409EFF;
      }
      
      &.disabled {
        color: #c0c4cc;
        cursor: not-allowed;
      }
    }
    
    /* 页码样式 */
    .el-pager {
      li {
        min-width: 32px;
        height: 32px;
        line-height: 32px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        background-color: #fff;
        margin: 0 4px;
        
        &:hover {
          color: #409EFF;
        }
        
        &.active {
          background-color: #409EFF;
          color: #fff;
          border-color: #409EFF;
        }
      }
    }
    
    /* 跳页输入框 */
    .el-pagination__jump {
      margin-left: 10px;
      
      .el-input {
        width: 50px;
        
        .el-input__inner {
          height: 32px;
          line-height: 32px;
          border-radius: 4px;
        }
      }
    }
    
    /* 每页条数选择器 */
    .el-pagination__sizes {
      margin-right: 10px;
      
      .el-select {
        .el-input {
          width: 100px;
          
          .el-input__inner {
            height: 32px;
            line-height: 32px;
            border-radius: 4px;
          }
        }
      }
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .pagination-wrapper {
    :deep(.el-pagination) {
      flex-wrap: wrap;
      justify-content: center;
      
      & > * {
        margin-bottom: 8px;
      }
    }
  }
  
  .filter-row {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-wrap: wrap;
    justify-content: flex-start;
    
    .el-button {
      margin-bottom: 10px;
    }
  }
}

.delete-btn {
  background: #fff;
  border: 1px solid #f56c6c;
  color: #f56c6c;
  transition: all 0.2s;
}
.delete-btn:hover {
  background: #f56c6c;
  color: #fff;
  border-color: #f56c6c;
}
</style>